package com.itheima.springboottlias.service.impl;

import com.itheima.springboottlias.annotation.SysLog;
import com.itheima.springboottlias.mapper.DeptMapper;
import com.itheima.springboottlias.mapper.EmpMapper;
import com.itheima.springboottlias.pojo.Dept;
import com.itheima.springboottlias.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author Taotao
 * @date 2023/7/15 20:46
 * @desciption:
 */
@Service
public class DeptServiceImpl implements DeptService {
    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private EmpMapper empMapper;
    @Override
    public List<Dept> selectList() {
        return deptMapper.selectList();
    }

    @Override
    @SysLog
    @Transactional(rollbackFor = Exception.class)
    public void deleteDept(Integer id) throws Exception {
        deptMapper.deleteDept(id);
      if(true){
          throw new Exception("错了");
      }
        empMapper.deleteByDeptId(id);

    }

    @Override
    @SysLog
    public void addDept(Dept dept) {
     Integer count =  deptMapper.selectCountByName(dept.getName());
     if(count > 0){
         throw new RuntimeException("部门已经存在~~换一个");
     }
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.addDept(dept);
    }
    /**
     * 根据id查找部门
     * @param id
     * @return
     */
    @Override
    public Dept selectById(Integer id) {
        Dept dept = deptMapper.selectById(id);
        return dept;
    }

    @Override
    public void updateById(Dept dept) {
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.updateById(dept);
    }
}
